/**
 * // Definition for a Node.
 * function Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {Node} root
 * @return {Node}
 */
 var connect = function(root) {
    let queue = [root]
    while(root!=null&&queue.length){        
        let len = queue.length;             
        for(let i =0;i<len;i++){
            let node = queue.pop();
            if(i<len-1){
                node.next = queue[queue.length-1]
            }
            node.left&&queue.unshift(node.left)
            node.right&&queue.unshift(node.right)
        }          
    }
    return root
};

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * } 104
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
 var maxDepth = function(root) {
    let res = 0;
    let queue = [root]
    while(root!=null&&queue.length){
        let len = queue.length;
        while(len--){
            let node = queue.pop()
            node.left&&queue.unshift(node.left)
            node.right&&queue.unshift(node.right)
        }
        res++
    }

    return res;
};


/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }111
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
 var minDepth = function(root) {
    let res = 0;
    let queue = [root]
    while(root!=null&&queue.length){
        let len = queue.length;
        res++
        while(len--){
            let node = queue.pop()
            node.left&&queue.unshift(node.left)
            node.right&&queue.unshift(node.right)
            if(node.left==null&&node.right==null){
                return res
            }
        }
        
    }

    return res;
};